package 常用类.Array类.list.List课堂案例;

import java.util.ArrayList;
import java.util.List;

public class UserOperate {
    //用于存储所有用户的List集合
    List<User> useList=new ArrayList<>();

    //1.添加用户
    public void addUser(User user) throws Exception {
        if (user==null){
            throw new Exception("用户为空");
        }
        useList.add(user);
    }

    //2.根据用户编号获得一个用户信息(有返回值 返回值为用户)
    public User getUserId(int userId){
        for (User user:useList){
            if (user.getUserId()==userId){
                return user;
            }
        }
        return null;
    }

    //3.修改某个用户的信息
    public void upDateUser(User user) throws Exception {
        User user1=this.getUserId(user.getUserId());
        if (user1==null){
            throw  new Exception("用户不存在");
        }
        user1.setUsername(user.getUsername());
        user1.setAge(user.getAge());
        user1.setEmail(user.getEmail());
        user1.setPassword(user.getPassword());
    }

    //4.根据用户编号删除用户信息
    public void deleteUserId(int userId) throws Exception {
        //根据值删除
        /*User user=this.getUserId(userId);
        if (user==null){
            throw new Exception("用户不存在");
        }
        useList.remove(user);*/

        //根据下标删除
        for (int i = 0; i < useList.size(); i++) {
            User user=useList.get(i);
            if (user.getUserId()==userId){
                useList.remove(i);
                return;
            }
        }
        throw new Exception("用户不存在");
    }

    //5.查看所有用户信息
    public void queryAll(){
        for (User user:useList){
            System.out.println(user);
        }
    }
}
